/*
 * Copyright 2008 The Brui Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
 
 package com.googlecode.brui.editors;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.JTextField;

/**
 * <p>Creates an editor for Strings based on their get/set methods.</p>
 * @author <a href="http://daemonsadvocate.blogspot.com/">The Daemons Advocate</a>
 * @version 1.0: 9/07/2008, 2:10:35 PM
 */
public class StringEditor extends JTextField {
	private static final long serialVersionUID = -5121273378029861104L;
	private static final Object[] GETTER_ARGS = new Object[0];
	
	public StringEditor(final Method getter, final Method setter, final Object instance) {
		super();
		
		// 0. Preconditions
		if(instance==null || getter==null || setter==null)
			throw new NullPointerException("Must specify all fields in Component Integer Constructor");
		
		try {
			// 1. Setup initial settings for this component. (display value)
			String text = (String)getter.invoke(instance, GETTER_ARGS);
			this.setText(text);

			// 2. Add a change listener so that changes are registered by the bean.
			this.addActionListener(
				new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent event) {
						// Pull the source and get at the new value
						StringEditor that = (StringEditor)event.getSource();
						Object[] args = { that.getText() };
						try {
							setter.invoke(instance, args);
						} // ...fail silently
						catch (IllegalArgumentException ex) { ex.printStackTrace(); }
						catch (IllegalAccessException ex) { ex.printStackTrace(); }
						catch (InvocationTargetException ex) { ex.printStackTrace(); }
					}
				}
			);
		}
		catch (IllegalArgumentException ex) { ex.printStackTrace(); }
		catch (IllegalAccessException ex) { ex.printStackTrace(); }
		catch (InvocationTargetException ex) { ex.printStackTrace(); }
	}
}
